package utils.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.ejb.Stateless;



@Stateless
public class SHAHashUtil {
    
    public String getHash(String content){
        try {
            byte[] contentBytes = content.getBytes("utf-8");
          
            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            messageDigest.update(contentBytes);
            byte[] digest = messageDigest.digest();
           
            return getHashString(digest);
            
        } catch (UnsupportedEncodingException ex) {
            System.err.println(ex);
        } catch (NoSuchAlgorithmException ex) {
            System.err.println(ex);
        }
        return null;
    }
    
    private String getHashString(byte[] digest){
        StringBuilder hashStringBuilder = new StringBuilder();
        for(byte b : digest){
             hashStringBuilder.append(String.format( "%02X", b & 0xff ));
        }
        return hashStringBuilder.toString();
    }
    
    public boolean verifyChecksum(String content, String testChecksum)
    {
        try{  
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");

            byte[] contentBytes = content.getBytes();
            messageDigest.update(contentBytes);
            byte[] hashBytes = messageDigest.digest();

            String hashString = getHashString(hashBytes);
            return hashString.equals(testChecksum);
        } catch (Exception ex){
            System.err.println(ex);
        }
        return false;
    }
    
    
    
}
